#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <dirent.h>

#include <sys/statfs.h> //for statfs
#include <sys/vfs.h> //for statfs

#include <sys/types.h>
#include <sys/stat.h> //for stat
#include <sys/time.h>
#include "errno.h"

static int nandflash_wrong=0;

char* ROOT_DIR = "/sdcard";
char TEST_DIR[128]={0};
char TEST_A[128]={0};
char TEST_B[128]={0};

/*
* 递归删除目录(删除该目录以及该目录包含的文件和目录)
* @dir:要删除的目录绝对路径
*/
int remove_dir(const char *dir)
{
    char cur_dir[] = ".";
    char up_dir[] = "..";
    char dir_name[128];
    DIR *dirp;
    struct dirent *dp;
    struct stat dir_stat;

    // 参数传递进来的目录不存在，直接返回
    if ( 0 != access(dir, F_OK) ) {
        return 0;
    }

    // 获取目录属性失败，返回错误
    if ( 0 > stat(dir, &dir_stat) ) {
        perror("get directory stat error");
        return -1;
    }

    if ( S_ISREG(dir_stat.st_mode) ) {  // 普通文件直接删除
        remove(dir);
    } else if ( S_ISDIR(dir_stat.st_mode) ) {   // 目录文件，递归删除目录中内容
        dirp = opendir(dir);
        while ( (dp=readdir(dirp)) != NULL ) {
            // 忽略 . 和 ..
            if ( (0 == strcmp(cur_dir, dp->d_name)) || (0 == strcmp(up_dir, dp->d_name)) ) {
                continue;
            }

            sprintf(dir_name, "%s/%s", dir, dp->d_name);
            remove_dir(dir_name);   // 递归调用
        }
        closedir(dirp);

        rmdir(dir);     // 删除空目录
    } else {
        perror("unknow file type!");    
    }

    return 0;
}

int check_remain_space(void)
{
    int stat_flag=0;
    int i;
    struct statfs nandflash_stat;
    long hdisk_remainder_space;
    char path_name_check[32];
    struct stat name_buf_check;

    stat_flag = statfs( TEST_DIR, &nandflash_stat);//获取nandflash的信息
    if(stat_flag<0)
    {
        printf("get nandflash info error!\n");
        return -1;
    }

    hdisk_remainder_space = (float)nandflash_stat.f_bsize * nandflash_stat.f_bfree / 1024;//检测磁盘空间
    if(hdisk_remainder_space<200*1024) //至少保留8M的空间
    {
        for(i=0;i<200;i++)
        {
            sprintf(path_name_check, "%s/A%d", TEST_DIR, i);
            stat(path_name_check,&name_buf_check);
            if(errno!=ENOENT) //文件存在，则删除
            {
                unlink(path_name_check);//不能重名 
            }
            sprintf(path_name_check, "%s/B%d", TEST_DIR, i);
            stat(path_name_check,&name_buf_check);
            if(errno!=ENOENT) //文件存在，则删除
            {
                unlink(path_name_check);//不能重名 
            } 
        }
        sleep(2); //删除文件并不是立即删除，所以要等待文件删除之后再写,防止写的速度比删除速度快，导致磁盘被写满的情况而出错 
        return 1;
    }

    return 0;
}

int write_read_nandflash(int mark,unsigned int i,int file_size,char *write_buf,char *read_buf)
{
    FILE *fp;
    char path_name[32];
    unsigned long buf_count=0;
    struct stat name_buf;

    if( mark == 0 )
    {
        sprintf(path_name, "%s/A%d", TEST_DIR, i);//生成不同的文件名A0，A1，A2，A3.......
    }
    else
    {
        sprintf(path_name, "%s/B%d", TEST_DIR, i);

    }

    stat(path_name,&name_buf);
    if(errno != ENOENT) //文件存在，则删除
    {
        unlink(path_name);//不能重名
        sleep(3);
    } 
    if((fp=fopen(path_name,"w"))==NULL)
    {
        printf("fopen failed!\n");
        return -1;
    }

    fwrite(write_buf,file_size,1,fp);
    fclose(fp);

    // printf("write file name is:%s\n",path_name);
    if((fp=fopen(path_name,"r"))==NULL)
    {
        printf("fopen failed!\n");
        return -1; 
    }
    fread(read_buf,file_size,1,fp);

    for(buf_count=0;buf_count<(file_size-1);buf_count++)//将master/slave文件写到nandflash中的内容读出来比较
    {
        if(read_buf[buf_count]!=write_buf[buf_count])
        {
            system("date");//出错的时候打印的系统时间
            printf("file name is %s:\n",path_name);
            unlink(path_name);
            sleep(3);
            if((fp=fopen(path_name,"w"))==NULL)
            {
                printf("fopen failed!\n");
                return -1;
            }
            nandflash_wrong++;
            fwrite(write_buf,file_size,1,fp);//出错之后再写一次
            fclose(fp);

            if((fp=fopen(path_name,"r"))==NULL)
            {
                printf("fopen failed!\n");
                return -1; 
            }
            fread(read_buf,file_size,1,fp);
            for(buf_count=0;buf_count<(file_size-1);buf_count++)
            {
                if(read_buf[buf_count]!=write_buf[buf_count])
                {
                    printf("file name is %s:\n",path_name);
                    printf("write twice failed!\n");
                    fclose(fp);
                    return -1;
                }
            }
        }
    }
    fclose(fp);
    return 0;
}

int main(int argc, char **argv)
{
    int A_size,B_size;
    A_size=B_size=0; 

    int A_fd,B_fd;

    char *A_buf_read=NULL;
    char *B_buf_read=NULL;
    char *A_buf_write=NULL;
    char *B_buf_write=NULL;

    unsigned int iteation=0;

    int ret;

    if(argc < 2) {
        printf("%s target_dir\n", argv[0]);
        return 0;
    }

    ROOT_DIR = argv[1];
    sprintf(TEST_DIR, "%s/test", ROOT_DIR);
    sprintf(TEST_A, "%s/A", ROOT_DIR);
    sprintf(TEST_B, "%s/B", ROOT_DIR);

    remove_dir( TEST_DIR );
    mkdir( TEST_DIR, 0755);

    A_fd=0;
    A_fd=open( TEST_A, O_RDONLY);
    if(A_fd<0)
    {
        printf("open A faild!\n");
        return -1;
    }
    A_size=lseek(A_fd,0,SEEK_END);
    lseek(A_fd,0,SEEK_SET);
    A_buf_write=(char *)malloc(A_size);

    if(NULL == A_buf_write)
    {
        printf("A_buf_write malloc failed!\n");
        close(A_fd);
        return -1;
    }

    A_buf_read=(char *)malloc(A_size);
    if(NULL == A_buf_read)
    {
        printf("A_buf_read malloc failed!\n");
        close(A_fd);
        return -1;
    }
    if(read(A_fd,A_buf_write,A_size)<0)
    {
        close(A_fd);
        printf("read A file failed\n");
    }

    close(A_fd);
    B_fd=0;
    B_fd=open( TEST_B,O_RDONLY);
    if(B_fd<0)
    {
        printf("open B faild!\n");
        return -1;
    }
    B_size=lseek(B_fd,0,SEEK_END);
    lseek(B_fd,0,SEEK_SET);
    B_buf_write=(char *)malloc(B_size);

    if(NULL == B_buf_write)
    {
        printf("B_buf_write malloc failed!\n");
        close(B_fd);
        return -1;
    }

    B_buf_read=(char *)malloc(B_size);
    if(NULL == B_buf_read)
    {
        printf("B_buf_read malloc failed!\n");
        close(B_fd);
        return -1;
    }
    if(read(B_fd,B_buf_write,B_size)<0)
    {
        printf("read B file failed\n");
        close(B_fd);
    }
    close(B_fd);
    system("date");//测试开始，开始读写nandflash
    while(1)
    {
        if((ret=check_remain_space())<0)//检测磁盘空间，小于8M,要删除文件重新从A0，B0，A1，B1，A2，B2。。。。写
        {
            printf("check space wrong\n");
            return -1;
        }
        else if(ret==1)
        {
            iteation=0;
        }
        if(write_read_nandflash(0,iteation,A_size,A_buf_write,A_buf_read)<0)//write A to nand and read it to compare 
        {
            printf("write_read nand flash wrong\n");
            return -1;
        }
        if(write_read_nandflash(1,iteation,B_size,B_buf_write,B_buf_read)<0)//write B
        {
            printf("write_read nand flash wrong\n");
            return -1;
        }
        iteation++;
    }
    return 0;
}